use git2::{ObjectType, Repository};
use serde::{Deserialize, Serialize};

/// git tag实体
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitTag {
    /// 提交id
    ///
    /// ## 示例: "92939508f87af17465e9274d245815edc9b764ca"
    pub commit_id: String,
    /// tag名称
    ///
    /// ## 示例: "v1.2.14"
    pub name: String,
}
/// 查询tag记录
pub fn git_read_tag(repo: &Repository) -> anyhow::Result<Vec<GitTag>> {
    let mut r = vec![];
    repo.tag_foreach(|oid, x| {
        let commit = repo.find_commit(oid).unwrap();
        let commit_id = commit.id().to_string();
        let name = std::str::from_utf8(x).unwrap()[10..].to_string();
        let tag = GitTag { commit_id, name };
        r.push(tag);
        true
    })?;
    Ok(r)
}
/// git tag git-tag-name
pub fn git_tag(repo: &Repository, msg: &str) -> anyhow::Result<()> {
    let reference = repo.head()?;
    let commit = reference.peel(ObjectType::Commit)?;
    repo.tag_lightweight(msg, &commit, false)?;
    Ok(())
}
